//
//  BaseWebController.m
//  Postre
//
//  Created by CoderLT on 2017/5/22.
//  Copyright © 2017年 CoderLT. All rights reserved.
//

#import "BaseWebController.h"
#import "UIViewController+ATKit.h"
#import <YYKit/YYKit.h>

@implementation NJKWebViewProgressView
- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}
- (void)awakeFromNib {
    [super awakeFromNib];
    [self setup];
}

- (void)setup {
    self.userInteractionEnabled = NO;
    self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    _progressBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, self.bounds.size.height)];
    _progressBarView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    UIColor *tintColor = [UIColor colorWithRed:22.f / 255.f green:126.f / 255.f blue:251.f / 255.f alpha:1.0]; // iOS7 Safari bar color
    if ([[UIBarButtonItem appearance] titleTextAttributesForState:UIControlStateNormal][NSForegroundColorAttributeName]) {
        tintColor = [[UIBarButtonItem appearance] titleTextAttributesForState:UIControlStateNormal][NSForegroundColorAttributeName];
    }
    else if ([UIApplication.sharedApplication.delegate.window respondsToSelector:@selector(setTintColor:)] && UIApplication.sharedApplication.delegate.window.tintColor) {
        tintColor = UIApplication.sharedApplication.delegate.window.tintColor;
    }
    _progressBarView.backgroundColor = tintColor;
    [self addSubview:_progressBarView];
    
    _barAnimationDuration = 0.27f;
    _fadeAnimationDuration = 0.27f;
    _fadeOutDelay = 0.1f;
}

- (void)setProgress:(float)progress {
    [self setProgress:progress animated:NO];
}
- (void)setProgress:(float)progress animated:(BOOL)animated {
    BOOL isGrowing = progress > 0.0;
    [UIView animateWithDuration:(isGrowing && animated) ? _barAnimationDuration : 0.0 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        CGRect frame = _progressBarView.frame;
        frame.size.width = progress * self.bounds.size.width;
        _progressBarView.frame = frame;
    } completion:nil];
    
    if (progress >= 1.0) {
        [UIView animateWithDuration:animated ? _fadeAnimationDuration : 0.0 delay:_fadeOutDelay options:UIViewAnimationOptionCurveEaseInOut animations:^{
            _progressBarView.alpha = 0.0;
        } completion:^(BOOL completed){
            CGRect frame = _progressBarView.frame;
            frame.size.width = 0;
            _progressBarView.frame = frame;
        }];
    }
    else {
        [UIView animateWithDuration:animated ? _fadeAnimationDuration : 0.0 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            _progressBarView.alpha = 1.0;
        } completion:nil];
    }
}
@end


static CGFloat _initProgress = 0.20f;
@interface BaseWebController ()
@end
@implementation BaseWebController
+ (instancetype)vcWithURLString:(NSString *)urlString {
    return [self vcWithURLString:urlString title:nil];
}
+ (instancetype)vcWithURLString:(NSString *)urlString title:(NSString *)title {
    BaseWebController *webView = [[self alloc] init];
    webView.urlString = urlString;
    webView.webNavTitle = title;
    return webView;
}

#pragma mark - lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self showNavTitle:self.webNavTitle backItem:YES];
    self.webView.backgroundColor = [UIColor appWebBackgroundColor];
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.webView.superview);
    }];
    [self.view addSubview:self.progressView];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.progressView.superview);
        make.top.equalTo(self.progressView.superview).offset(self.navigationController.navigationBar.isOpaque ? 0 : NAVI_HIGHT);
        make.height.equalTo(@(2.0f));
    }];
    
    [self setupEmpty:self.webView.scrollView];
    
    @weakify(self)
    [self.KVOController observe:self.webView keyPaths:@[@"title", @"canGoBack", @"estimatedProgress", @"scrollView.contentOffset"] options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {
        NSString *keyPath = change[FBKVONotificationKeyPathKey];
        @strongify(self)
        if ([keyPath isEqualToString:@"title"]) {
            [self setNavItemTitle:self.webNavTitle];
        }
        else if ([keyPath isEqualToString:@"canGoBack"]) {
            if ((self.navigationController.viewControllers.count == 1 && self.presentingViewController)
                || self.navigationController.viewControllers.count > 1) {
                UIBarButtonItem *fixItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
                fixItem.width = 12;
                UIImage *backImage = [UIImage imageNamed:@"nav_back"];
                if (self.webView.canGoBack) {
                    self.navigationItem.leftBarButtonItems = @[[self navItemWithImage:backImage title:(backImage ? nil : @"ㄑ") action:@selector(goBack)],
                                                               [self navItemWithImage:nil title:@"关闭" action:@selector(close)],
                                                               fixItem,
                                                               ];
                }
                else {
                    self.navigationItem.leftBarButtonItems = @[[self navItemWithImage:backImage title:(backImage ? nil : @"ㄑ")  action:@selector(goBack)]];
                }
            }
        }
        else if ([keyPath isEqualToString:@"estimatedProgress"]) {
            [self webViewRequestDidUpdateProgress:self.webView.estimatedProgress];
        }
        else if ([keyPath isEqualToString:@"scrollView.contentOffset"]) {
            if ([change[@"new"] CGPointValue].y == 0 && [change[@"old"] CGPointValue].y != 0 && [change[@"old"] CGPointValue].y == -self.webView.scrollView.contentInset.top) {
                self.webView.scrollView.contentOffset = CGPointMake(self.webView.scrollView.contentOffset.x, -self.webView.scrollView.contentInset.top);
            }
        }
    }];
    [self webViewRequestDidUpdateProgress:self.webView.estimatedProgress];
}

#pragma mark - 加载页面
- (void)setUrlString:(NSString *)urlString {
    _urlString = [urlString copy];
    [self headerRefreshing];
}
- (void)headerRefreshing {
    [super headerRefreshing];
    if (self.urlString.length > 0) {
        NSURL *url = [NSURL URLWithString:[self.urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]
                            relativeToURL:[NSURL URLWithString:self.baseURLString]];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [self.webView loadRequest:request];
        self.loadSuccess = NO;
        DLog(@"准备加载：%@", request.URL.absoluteString);
    }
    [self.webView.scrollView reloadEmptyDataSet];
}

// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    DLog(@"开始加载：%@", webView.URL.absoluteString);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [self webViewRequestDidStart];
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    DLog(@"开始接收：%@", webView.URL.absoluteString);
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    DLog(@"加载完成: %@",webView.URL.absoluteString);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    self.loadSuccess = YES;
    [self endRefresh:NO];
    [self setNavItemTitle:self.webNavTitle];
    [self webViewRequestingDidEnd];
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(nonnull NSError *)error {
    DLog(@"加载失败: %@",webView.URL.absoluteString);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [self endRefresh:NO];
    [self webViewRequestingDidEnd];
}

// 处理拨打电话
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSString *scheme= navigationAction.request.URL.scheme;
    if ([scheme isEqualToString:@"sms"] || [scheme isEqualToString:@"smsto"] || [scheme isEqualToString:@"mms"] || [scheme isEqualToString:@"mmsto"] || [scheme isEqualToString:@"tel"] || [scheme isEqualToString:@"mailto"]) {
        NSURL *url = navigationAction.request.URL;
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            if ([[UIApplication sharedApplication] respondsToSelector:@selector(openURL:options:completionHandler:)]) {
                if (@available(iOS 10.0, *)) {
                    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
                }
            }
            else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
                [[UIApplication sharedApplication] openURL:url];
#pragma clang diagnostic pop
            }
        }
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}


// js 里面的alert实现，如果不实现，网页的alert函数无效
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    [ATAlertView showTitle:nil message:message normalButtons:nil highlightButtons:@[@"确定"] completion:^(NSInteger index, NSString *buttonTitle) {
        completionHandler();
    }];
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    [ATAlertView showTitle:nil message:message normalButtons:@[@"取消"] highlightButtons:@[@"确定"] completion:^(NSInteger index, NSString *buttonTitle) {
        completionHandler(index == 1);
    }];
}

#pragma mark - actions

- (void)goBack:(BOOL)animated {
    if ([self.webView canGoBack]) {
        [self.webView goBack];
        return;
    }
    [super goBack:animated];
}

- (void)close {
    [super goBack:YES];
}

- (void)webViewRequestDidStart {
    [self webViewRequestDidUpdateProgress:self.webView.estimatedProgress];
}
- (void)webViewRequestingDidEnd {
}
- (void)webViewRequestDidUpdateProgress:(CGFloat)progress {
    progress = _initProgress + (1.0f - _initProgress) * progress;
    self.progressView.hidden = NO;
    [self.progressView setProgress:progress animated:YES];
    DLog(@"progressView  %.4f", progress);
}

#pragma mark - Empty delegate
- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    return !self.loadSuccess && !self.isRefreshing;
}

#pragma mark - getter
- (NSString *)baseURLString {
    if (_baseURLString) {
        return _baseURLString;
    }
    return nil;
}

- (NSString *)webNavTitle {
    if (_webNavTitle) {
        return _webNavTitle;
    }
    return self.webView.title;
}

- (WKWebView *)webView {
    if (!_webView) {
        WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc] init];
        configuration.allowsInlineMediaPlayback = YES;
        
        _webView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds configuration:configuration];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        if (@available(iOS 9.0, *)) {
            _webView.allowsLinkPreview = NO;
        }
    }
    return _webView;
}

- (NJKWebViewProgressView *)progressView {
    if (!_progressView) {
        CGFloat progressBarHeight = 2.f;
        CGRect navigationBarBounds = self.navigationController.navigationBar.bounds;
        CGRect barFrame = CGRectMake(0, navigationBarBounds.size.height - progressBarHeight, navigationBarBounds.size.width, progressBarHeight);
        _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
        _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
        _progressView.hidden = YES;
        _progressView.progressBarView.backgroundColor = [UIColor appColor];
    }
    return _progressView;
}
@end
